<?php
namespace app\controller;

use app\BaseController;
use app\Request;
use think\App;
use think\cache\driver\Redis;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Queue;

class Index extends BaseController
{

    protected $redis;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1',6379);
        $this->redis->auth('123456');
    }

    public function test()
    {
        $id = 1;

        $goodsInfo = Db::name('goods')->where(["id"=>$id])->find();
        Cache::set('good_info_'.$id,$goodsInfo);
        //设定商品数量
        $count=$goodsInfo['count'];
        $listKey="goods_list_".$id;
        for ($i=1;$i<=$count;$i++){
            //将商品库存到列表中
            $this->redis->lPush($listKey,$i);
        }
    }

    /**
     * 用户下单  数据库先不做库存增减   用户付款完成之后再做可以做到数据同步
     * @return bool
     */
    public function createOrder()
    {
        $id = \think\facade\Request::param('id');

        try {
/*            if ($this->redis->lLen('goods_list') == 0)
            {
                $this->numberCache($id);
            }*/
            $listKey = 'goods_list_'.$id;
            $countNum = $this->redis->lpop($listKey);//减少库存
            $lengthKey = $this->redis->lLen($listKey); //计算长度
            //减少库存并且判断库存数量是否为0
            if ($lengthKey <= 0  && $countNum <= 0)
            {
                return error('抢购活动结束');
                return false;
            }else
            {
                $goodsInfos = Cache::get('good_info_'.$id);
                $orderData = [
                    'order_sn'=>order_sn(),    //订单号调用方法生成
                    'user_id'=>1,
                    'goods_id'=>$id,              //传过来的商品id
                    'price'=>$goodsInfos['amount'],
                    'addtime'=>time(),
                ];
                $jobHandlerClassName = 'app\job\Task';
                $jobQueueName = 'task';
                $isPushed = \think\facade\Queue::push($jobHandlerClassName, $orderData, $jobQueueName);
                if ($isPushed)
                {
                    Log::info("----------------------------------商品入队列成功-------------------------------------");
                    return success($orderData,'创建订单成功！',200);
                }else
                {
                    return error('创建订单失败！',$orderData,400);
                    Log::info("----------------------------------商品入队列失败-------------------------------------");
                }
            }
            echo $this->redis->lLen($listKey);
        }catch (\Exception $exception)
        {
            return error($exception->getCode().$exception->getMessage().$exception->getLine());
        }

    }

    /**
     * 库存加入缓存
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function numberCache($id)
    {
        $id = 1;
        try {
            $goodsInfo = Db::name('goods')->where(["id"=>$id])->find();
            Cache::set('good_info_'.$id,$goodsInfo);
            //设定商品数量
            $count=$goodsInfo['count'];
            $listKey="goods_list_".$id;
            for ($i=1;$i<=$count;$i++){
                //将商品库存到列表中
                $this->redis->lPush($listKey,$i);
            }
            return true;
        }catch (\RedisException $redisException){
            echo $redisException->getMessage().$redisException->getCode();
            return false;
        }catch (\Exception $exception)
        {
            echo $exception->getMessage().$exception->getCode();
            return false;
        }

    }


}
